package com.ld.wms.utils;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

public class ExcelUtils {

    public static String generateExcel(List<String> titleList, List<List<String>> dataList) {
        // 创建一个新的工作簿
        Workbook workbook = new XSSFWorkbook();
        // 创建一个工作表
        Sheet sheet = workbook.createSheet("ExampleSheet");
        // 设置标题
        // 创建行（0基索引）
        Row row = sheet.createRow(0);
        for (int i = 0; i < titleList.size(); i++) {
            // 创建单元格并设置值
            Cell cell = row.createCell(i);
            cell.setCellValue(titleList.get(i));
        }

        // 设置内容
        for (int i = 1; i <= dataList.size(); i++) {
            // 设置行数
            row = sheet.createRow(i);
            List<String> objects = dataList.get(i - 1);
            for (int j = 0; j < objects.size(); j++) {
                Cell cell = row.createCell(j);
                cell.setCellValue(objects.get(j));
            }
        }
        // 写入到文件
        String path = "";
        try {
            path = "D:/home/excel/" + System.currentTimeMillis() + ".xlsx";
            FileOutputStream fileOutputStream = new FileOutputStream(path);
            OutputStream outputStream = fileOutputStream;
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 清理资源
            try {
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return path;
    }
}
